<?php

namespace app\lib;

require_once APP_PATH . 'lib/luosimaoSms/src/Sms.php';

//use Qcloud\Sms\SmsSingleSender;
use Leslie\Sms\Sms as SmsSender;

use think\Exception;

class Sms
{

    protected $appId;
    protected $appKey;
    protected $smsSign = '';
    protected $templateId = '';

    function __construct()
    {
//        $this->appId = config('sms.AppID');
//        $this->appKey = config('sms.AppKey');
//        $this->smsSign = config('sms.Sign');
//        $this->templateId = config('sms.templateId');

    }

    /**
     * 发送短信 (腾讯云)
     *
     * @param $phone
     * @return bool|mixed
     */
    /*public function send($phone){
        try {
            $ssender = new SmsSingleSender($this->appId,$this->appKey);
            $key = randString(4);
            $params = [$key];
            $result = $ssender->sendWithParam("86",$phone,$this->templateId,$params,$this->smsSign,"","");
            $data = json_decode($result,true);
            $data['code'] = $key;
            return $data;
        } catch (Exception $e) {
            return false;
        }
    }*/

    /**
     * 发送短信 (Luosimao)
     *
     * @param $phone
     * @return bool|mixed
     */
    public function send($phone){
        try {
            $apiKey = config('sms.api_key');
            $sms = new SmsSender(['api_key' => $apiKey, 'use_ssl' => false]);

            $key = $this->randString(4);
            $template = "验证码：{$key}【秒到小程序】";
            $result = $sms->send($phone, $template);
            $data = $result;
            $data['code'] = $key;
            return $data;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * 发送会议短信提醒
     * @param $phone
     * @param string $template
     * @return bool|mixed
     */
    public function sendMsg($phone,$template = "【秒到小程序】"){
        try{
            $apiKey = config('sms.api_key');
            $sms = new SmsSender(['api_key' => $apiKey, 'use_ssl' => false]);
            $result = $sms->send($phone, $template);
            return $result;
        }catch (Exception $e){
            return false;
        }
    }

    /**
     * 生成随机验证码
     * @param int $len
     * @return bool|string
     */
    public function randString($len = 6)
    {
        $chars = str_repeat('0123456789', 3);
        // 位数过长重复字符串一定次数
        $chars = str_repeat($chars, $len);
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }
}